package com.lkj.utils;

import com.lkj.common.Constant;
import com.lkj.config.FileConfig;
import com.lkj.exception.FileException;
import com.lkj.exception.FileNameLengthLimitException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author likanjie
 * @Date 2020/9/7 9:28 下午
 */
public class FileUploadUtils {

    /**
     * 默认文件大小
     */
    public static final long DEFAULT_FILE_SIZE = 50 * 1024 * 1024;

    /**
     * 默认文件名长度
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    public static String upload(String baseDir,MultipartFile file) throws IOException {

        try {
            return upload(baseDir, file,MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(),e);
        }
    }

    public static String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws IOException {

        //检查文件名长度
        String originalFilename = file.getOriginalFilename();
        if (originalFilename.length() > DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitException(DEFAULT_FILE_NAME_LENGTH);
        }
        //检查文件大小、检查文件指定类型
        assertAllowed(file,allowedExtension);

        //编码文件名
        String fileName = extractFileName(file);

        //获取路径保存到本地
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);

        //返回路径
        String pathFileName = getPathFileName(baseDir,fileName);

        return pathFileName;
    }

    public static String getPathFileName(String baseDir,String fileName){

        int length = FileConfig.getProfile().length()+1;

        String currentDir = baseDir.substring(length);

        String pathFileName = Constant.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        return pathFileName;
    }

    public static File getAbsoluteFile(String dir,String fileName) throws IOException {

        File desc = new File(dir+File.separator+fileName);
        if (!desc.getParentFile().exists()){

            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }

        return desc;
    }



    public static String extractFileName(MultipartFile file) {

        String filename = file.getOriginalFilename();

        String extension = getExtension(file);

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String currentDate = format.format(new Date());

        long l = System.currentTimeMillis();
        String s = String.valueOf(l);

        filename = currentDate +"/"+ s + "."+extension;

        return filename;
    }




    public static void assertAllowed(MultipartFile file,String[] allowedExtension){

        long size = file.getSize();
        if (size !=-1 && size > DEFAULT_FILE_SIZE) {
            throw new FileException("500","文件过大");
        }

        String extension = getExtension(file);

        if (allowedExtension != null && !isAllowedExtension(extension,allowedExtension)) {

            throw new FileException("500","不允许文件类型");

        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static boolean isAllowedExtension(String extension,String[] allowedExtension){

        for (String s : allowedExtension) {
            if (s.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     * @param file
     * @return
     */
    public static String getExtension(MultipartFile file){

        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}
